import { allNewProvinceList, allNewCityList, allNewAreaList } from '@hs-admin/utils'
import { useImmer } from 'use-immer'

export function getAreaOptions() {
  const prev = allNewProvinceList.map((item) => ({
    ...item,
    type: 'province',
    children: []
  }))
  prev.forEach((first: { children: any[]; value: string | number }) => {
    first.children = allNewCityList[first.value]?.map((item) => ({
      ...item,
      type: 'city',
      children: [],
      province: first.value
    }))
    first.children?.forEach((second: any) => {
      second.children = allNewAreaList[second.value]?.map((item) => ({
        ...item,
        type: 'district',
        city: second.value,
        province: first.value
      }))
      second.children = second.children?.filter((third: { label: string }) => third.label !== '市辖区')
    })
  })
  return prev
}

export const useTableCheck = () => {
  const [selectedRowKeys, setselectedRowKeys] = useImmer<any[]>([])
  const [selectedData, setselectedData] = useImmer<any[]>([])
  const rowSelection = {
    onSelect: (record: any, selected: boolean) => {
      if (selected) {
        setselectedRowKeys((prevState) => {
          prevState.push(record.data_id)
        })
        setselectedData((prevState) => {
          prevState.push(record)
        })
      } else {
        setselectedRowKeys((prevState) => {
          const index = prevState.findIndex((ele) => ele === record.data_id)
          prevState.splice(index, 1)
        })
        setselectedData((prevState) => {
          const index = prevState.findIndex((ele) => ele.data_id === record.data_id)
          prevState.splice(index, 1)
        })
      }
    },
    onSelectAll: (selected: boolean, _selectedRows: any[], changeRows: any[]) => {
      if (selected) {
        setselectedRowKeys((prevState) => {
          const ids = changeRows.map((item: any) => item.data_id)
          prevState = [...prevState, ...ids]
          return prevState
        })
        setselectedData((prevState) => {
          prevState = [...prevState, ...changeRows]
          return prevState
        })
      } else {
        setselectedRowKeys((prevState) => {
          const ids = changeRows.map((item: any) => item.data_id)
          ids.forEach((item: string) => {
            const index = prevState.findIndex((ele) => ele === item)
            prevState.splice(index, 1)
          })
        })
        setselectedData((prevState) => {
          changeRows.forEach((ele: any) => {
            const index = prevState.findIndex((item) => item.data_id === ele.data_id)
            prevState.splice(index, 1)
          })
        })
      }
    }
  }

  return {
    selectedRowKeys,
    setselectedRowKeys,
    selectedData,
    setselectedData,
    rowSelection
  }
}
